package com.huarui.part.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;

import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.model.Dictionary;
import com.huarui.dictionary.service.DictionaryService;
import com.huarui.params.Params;
import com.huarui.part.model.MeasurementUnit;
import com.huarui.part.model.Part;
import com.huarui.part.model.PartCategory;
import com.huarui.part.model.PartProperty;
import com.huarui.part.service.PartService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.JsonUtil;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

public class PartAction extends BaseAction {

	private static final long serialVersionUID = 2924526709280705961L;
	private static final Logger log = Logger.getLogger(PartAction.class);
	private PartService partService;

	private DictionaryService dictionaryService;

	private Part part;

	private ListModel<Part> partListModel;

	private String code;

	private int source;

	public int getSource() {
		return source;
	}

	public void setSource(int source) {
		this.source = source;
	}

	private String dir;

	private String sort;

	private int start;

	private int limit;

	private String queryParam;

	private Map<String, Object> mesMap;

	private Map<String, Object> resultMap;

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public void setResultMap(Map<String, Object> resultMap) {
		this.resultMap = resultMap;
	}

	private JSONObject jsonResult;
	/**
	 * 计量单位列表
	 */
	private List<MeasurementUnit> unitList;
	/**
	 * 零件一级类别列表
	 */
	private List<PartCategory> categoryLeve1List;
	/**
	 * 零件子类别列表
	 */
	private List<PartCategory> categorySubList;

	/**
	 * 耐用性
	 */
	private List<Dictionary> durabilityList;

	/**
	 * 来源
	 */
	private List<Dictionary> sourceList;
	
	private String json;
	public Map<String, Object> getMesMap() {
		return mesMap;
	}

	public void setMesMap(Map<String, Object> mesMap) {
		this.mesMap = mesMap;
	}

	public String toList() {

		partListModel = new ListModel();

		partListModel.setResult(partService.getPartList());

		return "toList";
	}

	public String toAdd() {

		unitList = partService.getAllUnits();
		categoryLeve1List = partService.getCategoryLevelList();
		durabilityList = dictionaryService
				.getSubDictionaryListByGroup(DictionaryEnum.GROUP_DURABILITY
						.toString());
		sourceList = dictionaryService
				.getSubDictionaryListByGroup(DictionaryEnum.GROUP_SOURCE
						.toString());
		return "input";
	}

	@Validations(requiredStrings = { @RequiredStringValidator(fieldName = "part.name", key = "part.name.required") })
	public String doAdd() {

		part.setCompanyId(1);
		part.setPyCode("");

		part.setLevel2Name("");
		PartCategory category1 = partService
				.getCategoryById(part.getLevel1Id());
		part.setLevel1Name(category1.getLevel1Name());
		if (part.getPartCategoryId() == 0) {
			part.setPartCategoryId(part.getLevel1Id());
		} else {
			PartCategory category2 = partService.getCategoryById(part
					.getPartCategoryId());
			part.setLevel1Name(category2.getLevel2Name());

		}
		// 查询类别名称

		partService.createPart(part);
		return SUCCESS;
	}

	public String toModi() {

		unitList = partService.getAllUnits();
		categoryLeve1List = partService.getCategoryLevelList();
		durabilityList = dictionaryService
				.getSubDictionaryListByGroup(DictionaryEnum.GROUP_DURABILITY
						.toString());
		sourceList = dictionaryService
				.getSubDictionaryListByGroup(DictionaryEnum.GROUP_SOURCE
						.toString());
		part = partService.getPartById(part.getId());
		return "toModi";
	}

	/**
	 * 根据code，source查找partProperty
	 */
	public String getPartByCodeAndSource() {
		try {

			Object partProperty = partService
					.getPartPropertyByConditions(queryParam);
			jsonResult = JSONObject.fromObject(partProperty);		
			jsonResult.put("success", true);
		} catch (Exception e) {
			log.error("查询零件属性信息失败....", e);
			jsonResult.put("success", false);
			jsonResult.put("msg", "查询零件属性信息失败....");
		}
		return SUCCESS;
	}

	/**
	 * combox 根据零件code模糊查找
	 */
	@SuppressWarnings("unchecked")
	public String getPartByCodeImplicitExt() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code_prefix", queryParam);
		ListModel lm = generateListModelParams();
		ListModel partList = partService.getPartCodeListByConditions(lm, map);
		// JSONArray partArray = JSONArray.fromObject(partList.getResult());
		jsonResult = new JSONObject();
		jsonResult.put("root", partList.getResult());
		jsonResult.put("totalProperty", partList.getTotal());
		return SUCCESS;
	}

	/**
	 * 后台查询
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String listPart() {
		Map<String, Object> paramsMap = null;
		if (queryParam == null) {
			paramsMap = new HashMap<String, Object>();
		} else {
			JSONObject jo = JSONObject.fromObject(queryParam);
			paramsMap = (Map<String, Object>) JSONObject.toBean(jo,
					HashMap.class);
		}

		ListModel lm = new ListModel();
		lm.setPageSize(Params.BACKGROUND_PAGE_SIZE);
		lm.setStart(start);

		List<Map> partList = partService.getPartListByConditions(lm, paramsMap);
		mesMap = new HashMap<String, Object>();
		mesMap.put("root", partList);
		mesMap.put("totalProperty", lm.getTotal());
		return SUCCESS;
	}

	public String query() throws IOException {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json; charset=UTF-8");// 处理中文问题的必须的代码
		PrintWriter out = response.getWriter();
		ListModel<Part> lm = new ListModel<Part>();
		lm.setPageSize(limit);
		lm.setStart(start);
		lm.setOrderBy(sort);
		lm.setDesc(dir.equals("desc") ? true : false);
		ListModel<Part> listModel = partService.getAllParts(lm);
		JSONObject jsonObject = new JSONObject();
		JSONArray jarray = JSONArray.fromObject(listModel.getResult());
		// 分页信息
		jsonObject.put("totalProperty", listModel.getTotal());
		jsonObject.put("page", lm.getPage());
		jsonObject.put("root", jarray);
		out.print(jsonObject.toString());

		return null;

	}

	public String queryCombox() throws IOException {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json; charset=UTF-8");// 处理中文问题的必须的代码
		PrintWriter out = response.getWriter();
		ListModel<Part> lm = new ListModel<Part>();

		lm.setPageSize(limit);
		lm.setStart(start);
		ListModel<Part> listModel = partService
				.getAllComboxPart(lm, queryParam);
		JSONObject jsonObject = new JSONObject();
		JSONArray jarray = JSONArray.fromObject(listModel.getResult());
		// 分页信息
		jsonObject.put("totalProperty", listModel.getTotal());
		jsonObject.put("page", lm.getPage());
		jsonObject.put("root", jarray);
		out.print(jsonObject.toString());
		return null;

	}

	@SuppressWarnings("unchecked")
	private ListModel generateListModelParams() {
		ListModel listModel = new ListModel();
		listModel.setPageSize(limit == 0 ? 10 : limit);
		listModel.setStart(start);
		listModel.setOrderBy(sort);
		if (dir != null)
			listModel.setDesc(dir.equals("DESC") ? true : false);
		return listModel;
	}

	public String getPartWithCodeAndSource() {

		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		JSONObject queryObject = JSONObject.fromObject(queryParam);
		Map<String, Object> queryMap = (Map<String, Object>) JSONObject.toBean(
				queryObject, Map.class);
		code = queryMap.get("code") == null ? "" : queryMap.get("code")
				.toString();
		String s = queryMap.get("source") == null ? "0" : queryMap
				.get("source").toString();
		try {
			source = Integer.parseInt(s);
		} catch (NumberFormatException e) {
			log.error("零件来源错误");
			source = 0;

		}

		Part part = partService.getPartByCodeAndSource(queryMap.get("code")
				.toString(), source, sm.getCompanyId());
		jsonResult = new JSONObject();
		if (part != null) {
			jsonResult = JSONObject.fromObject(part);
			jsonResult.put("success", "true");
		} else {
			jsonResult.put("success", "false");
			jsonResult.put("msg", "查询零件属性信息失败....");
		}
		return SUCCESS;
	}
	public String findPartByCodeAndSource(){
		Part part=JsonUtil.getBean(json, Part.class);
		resultMap=partService.findPartByCodeAndSource(part);
		return SUCCESS;
	}
	public String doModi() {

		JSONObject jo = JSONObject.fromObject(queryParam);

		Part part = (Part) JSONObject.toBean(jo, Part.class);
		part.setName(part.getName().trim());
		part.setNameEn(part.getNameEn().trim());
		resultMap = partService.updatePart(part);

		return JSON;
	}
	public Part getPart() {
		return part;
	}

	public void setPart(Part part) {
		this.part = part;
	}

	public List<MeasurementUnit> getUnitList() {
		return unitList;
	}

	public void setUnitList(List<MeasurementUnit> unitList) {
		this.unitList = unitList;
	}

	public List<PartCategory> getCategoryLeve1List() {
		return categoryLeve1List;
	}

	public void setCategoryLeve1List(List<PartCategory> categoryLeve1List) {
		this.categoryLeve1List = categoryLeve1List;
	}

	public List<PartCategory> getCategorySubList() {
		return categorySubList;
	}

	public void setCategorySubList(List<PartCategory> categorySubList) {
		this.categorySubList = categorySubList;
	}

	public void setPartService(PartService partService) {
		this.partService = partService;
	}

	public ListModel<Part> getPartListModel() {
		return partListModel;
	}

	public void setPartListModel(ListModel<Part> partListModel) {
		this.partListModel = partListModel;
	}

	public List<Dictionary> getDurabilityList() {
		return durabilityList;
	}

	public void setDurabilityList(List<Dictionary> durabilityList) {
		this.durabilityList = durabilityList;
	}

	public List<Dictionary> getSourceList() {
		return sourceList;
	}

	public void setSourceList(List<Dictionary> sourceList) {
		this.sourceList = sourceList;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimit() {
		return limit;
	}

	public String getQueryParam() {
		return queryParam;
	}

	public void setQueryParam(String queryParam) {
		this.queryParam = queryParam;
	}

	public JSONObject getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(JSONObject jsonResult) {
		this.jsonResult = jsonResult;
	}

	public void setJson(String json) {
		this.json = json;
	}

}
